<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
// 按需引入 引入 ECharts 主模块
var echarts = require('echarts/lib/echarts')
// 引入柱状图
require('echarts/lib/chart/line')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
import resize from './mixins/resize'
export default {
  mixins: [resize],
  props: {
    title: {
      type: Object,
      default: () => {
        return {}
      }
    },
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    // 直角坐标系网格
    grid: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 提示框
    tooltip: {
      type: Object,
      default: () => {
        return {
          trigger: 'axis'
        }
      }
    },
    // 直角坐标系x轴
    xAxis: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 直角坐标系y轴
    yAxis: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 图例
    legend: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 颜色
    color: {
      type: Array,
      default: () => {
        return ['#409eff', '#4cd964']
      }
    },
    seriesData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    seriesData: {
      handler() {
        this.setOptions()
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el)
      this.setOptions()
    },
    setOptions() {
      const chartObj = {}
      chartObj.title = this.title
      chartObj.grid = this.grid
      chartObj.xAxis = this.xAxis
      chartObj.yAxis = this.yAxis
      chartObj.legend = this.legend
      chartObj.color = this.color
      chartObj.tooltip = this.tooltip
      chartObj.series = this.seriesData
      this.chart.setOption(chartObj)
    }
  }
}
</script>
